<template>
  <div>
    <template v-if="poster">
      <div class="flex">
        <!-- @mousewheel.prevent="rollImg" @mousedown.prevent="moveImg" -->
        <div class="poster_wrap flex flex-a-c mr-10 overflow-hidden" ref="imgWrap" @mousewheel.prevent="rollImg">
          <a-image width="250" height="444.7" :src="poster" show-loader :preview="false" alt="活动图片" fit="cover">
          </a-image>
          <img
            ref="image"
            :style="{
              top: picT + 'px',
              left: picL + 'px',
              objectFit: 'cover',
              width: (picW || 200 / 3) + 'px',
              height: (picW || 200 / 3) + 'px'
            }"
            @mousedown.prevent="moveImg"
            class="qr_wrap"
            src="@/assets/images/app_down_code.png"
            alt="二维码"
          />
          <div
            @click="centerPoster"
            class="m-absolute t-10 r-66 round-50-p w-26 h-26 flex-center cursor-pointer"
            style="background: rgba(25, 25, 25, 0.5)"
          >
            <a-tooltip content="二维码水平居中">
              <icon-align-center class="text-size-16 textfff" />
            </a-tooltip>
          </div>
          <div
            class="m-absolute t-10 r-36 round-50-p w-26 h-26 flex-center cursor-pointer"
            style="background: rgba(25, 25, 25, 0.5)"
          >
            <a-upload
              :file-list="fileList"
              :show-file-list="false"
              :action="uploadImage()"
              :headers="{ Authorization: token }"
              :multiple="false"
              name="file"
              :on-before-upload="
                () => {
                  return (loading = true)
                }
              "
              @success="handleUploadSuccess"
              @error="handleUploadError"
            >
              <template #upload-button>
                <a-tooltip content="海报重新上传">
                  <icon-refresh class="text-size-16 textfff" />
                </a-tooltip>
              </template>
            </a-upload>
          </div>
          <div
            @click="deletePoster"
            class="m-absolute t-10 r-6 round-50-p w-26 h-26 flex-center cursor-pointer"
            style="background: rgba(25, 25, 25, 0.5)"
          >
            <a-tooltip content="删除海报">
              <icon-delete class="text-size-16 textfff" />
            </a-tooltip>
          </div>
        </div>
        <div class="round-10 bg64f0f6fd box-border p-m" style="height: fit-content">
          <div class="font-bold mb-10">海报二维码样式</div>
          <div class="flex flex-a-c mt-m">
            <label class="nowrap text666 w-11n text-align-left">宽/高：</label>
            <a-input-number
              class="w-22n"
              :model-value="width"
              placeholder="请输入"
              :min="0"
              :max="750"
              @change="inputChangeWidth"
            />
          </div>
          <div class="flex flex-a-c mt-m">
            <label class="nowrap text666 w-11n text-align-left">距左：</label>
            <a-input-number class="w-22n" :model-value="left" placeholder="请输入" :min="0" @change="inputChangeLeft" />
          </div>
          <div class="flex flex-a-c mt-m text-align-left">
            <label class="nowrap text666 w-11n">距上：</label>
            <a-input-number class="w-22n" :model-value="top" placeholder="请输入" :min="0" @change="inputChangeTop" />
          </div>
        </div>
      </div>
    </template>
    <div class="mb-6" v-else>
      <a-upload
        :file-list="fileList"
        :show-file-list="false"
        :action="uploadImage()"
        :headers="{ Authorization: token }"
        :multiple="false"
        name="file"
        :on-before-upload="
          () => {
            return (loading = true)
          }
        "
        @success="handleUploadSuccess"
        @error="handleUploadError"
      >
        <template #upload-button>
          <a-button type="primary" size="small" :loading="loading">
            <template #icon>
              <icon-to-top />
            </template>
            <span>上传</span>
          </a-button>
        </template>
      </a-upload>
    </div>
  </div>
</template>

<script setup>
import { uploadImage } from '@/apis'
import { getToken } from '@/utils/auth'
import { Message } from '@arco-design/web-vue'
defineOptions({ name: 'MsPoster' })
// 上传组件需要增加token
const tokenSource = getToken()
const token = tokenSource ? `Bearer ${tokenSource}` : ''
const emit = defineEmits(['update:poster', 'update:width', 'update:height', 'update:top', 'update:left', 'resetPoster'])
const loading = ref(false)
const fileList = ref([])
const realFileList = ref([]) //真实的上传列表
const imgWrap = ref()
const image = ref()
const props = defineProps({
  poster: {
    default: '',
    type: String
  },
  width: {
    default: undefined,
    type: [Number, String]
  },
  top: {
    default: undefined,
    type: [Number, String]
  },
  left: {
    default: undefined,
    type: [Number, String]
  },
  showReset: {
    default: false,
    type: Boolean
  },
  mousewheel: {
    default: true,
    type: Boolean
  }
})
let picWO = null
let picTO = null
let picLO = null

const picW = computed(() => {
  return props.width / 3
})
const picT = computed(() => {
  return props.top / 3
})
const picL = computed(() => {
  return props.left / 3
})
const deletePoster = () => {
  emit('update:poster', undefined)
  emit('update:width', undefined)
  emit('update:top', undefined)
  emit('update:left', undefined)
}
const resetPoster = () => {
  emit('update:width', picWO)
  emit('update:top', picTO)
  emit('update:left', picLO)
}
const centerPoster = () => {
  const widthO = props.width || 200
  emit('update:left', Math.round((750 - widthO) / 2))
}
// 上传图片成功改变
const handleUploadSuccess = (fileItem) => {
  realFileList.value = [
    {
      uid: fileItem.uid,
      name: fileItem.name,
      url: fileItem.response.data.url
    }
  ]
  loading.value = false
  emit('update:poster', fileItem.response.data.url)
}
// 上传失败
const handleUploadError = (e) => {
  loading.value = false
  Message.error(e.response.message)
}
watch(
  () => props.poster,
  (str) => {
    if (str) {
      fileList.value = [
        {
          uid: 1,
          name: '1.png',
          url: str
        }
      ]
    } else {
      fileList.value = []
    }
    realFileList.value = JSON.parse(JSON.stringify(fileList.value))
  },
  { deep: true, immediate: true }
)

const rollImg = (e) => {
  if (!props.mousewheel) return
  let transform = image.value.style.transform
  let zoom = transform.indexOf('scale') != -1 ? +transform.split('(')[1].split(')')[0] : 1
  zoom += e.wheelDelta / 1200
  if (zoom > 0.5 && zoom < 2.5) {
    emit('update:width', Math.round(props.width * zoom))
  }
}

const moveImg = (e) => {
  let wrap = imgWrap.value
  let img = image.value
  let x = e.pageX - img.offsetLeft
  let y = e.pageY - img.offsetTop
  // 添加鼠标移动事件
  wrap.addEventListener('mousemove', move)
  function move(e) {
    let xo = e.pageX - x
    let to = e.pageY - y
    const wo = picW.value
    if (xo < 0) xo = 0
    if (xo > 250 - wo) xo = 250 - wo
    if (to < 0) to = 0
    if (to > 444.7 - wo) to = 444.7 - wo
    emit('update:left', Math.round(xo * 3))
    emit('update:top', Math.round(to * 3))
  }
  // 添加鼠标抬起事件，鼠标抬起，将事件移除
  img.addEventListener('mouseup', () => {
    wrap.removeEventListener('mousemove', move)
  })
  // 鼠标离开父级元素，把事件移除
  wrap.addEventListener('mouseout', () => {
    wrap.removeEventListener('mousemove', move)
  })
}

const inputChangeWidth = (e) => {
  emit('update:width', e)
}
const inputChangeHeight = (e) => {
  emit('update:height', e)
}
const inputChangeTop = (e) => {
  emit('update:top', e)
}

const inputChangeLeft = (e) => {
  emit('update:left', e)
}
</script>
<style lang="scss" scoped>
.poster_wrap {
  width: 250px;
  height: 444.7px;
  position: relative;
  .qr_wrap {
    position: absolute;
    cursor: move;
  }
}
.bg64f0f6fd {
  background: rgb(var(--primary-1));
}
</style>
